package com.example.order.controller;

import com.example.order.client.ProductClient;
import com.example.order.converter.OrderFrom2OrderDTO;
import com.example.order.dto.OrderDTO;
import com.example.order.enums.ResultEnum;
import com.example.order.exeception.OrderExeception;
import com.example.order.from.OrderFrom;
import com.example.order.service.OrderMasterService;
import com.example.order.util.Console;
import com.example.order.util.ReslutVoUtil;
import com.example.order.vo.ReslutVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private  ProductClient productClient;

    @RequestMapping("/create")
    @ResponseBody
    public ReslutVo create(@Valid OrderFrom orderFrom, BindingResult BindingResult){
        if(BindingResult.hasErrors()){
             //创建订单失败
            throw  new OrderExeception(ResultEnum.PARAM_ERROR.getCode(),BindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO orderDTO = OrderFrom2OrderDTO.convert(orderFrom);
        if(CollectionUtils.isEmpty(orderDTO.getOderDetaillist())){
            Console.log("购物车为空");
            throw  new OrderExeception(ResultEnum.CART_EMPTY);
        }
        OrderDTO dto = orderMasterService.create(orderDTO);


        Map<String,String> map  = new HashMap<>();
        map.put("orderId",dto.getOrderId());
        return ReslutVoUtil.sucess(map);
    }

    @RequestMapping("/finish")
    @ResponseBody
    public ReslutVo finish(String orderId){
        return  ReslutVoUtil.sucess(orderMasterService.finish(orderId));
    }
}
